from django.db import models
from dingxiang.utils.models import BaseModel
from users.models import UserModel
from doctors.models import DoctorModel


# Create your models here.


class OrderModel(BaseModel):
    ORDER_STATUS_CHOICES = (
        (0, '待支付'),
        (1, '已支付'),
        (2, '已取消'),
        (3, '已超时')
    )

    PAY_TYPE_CHOICES = (
        (0, '微信支付'),
        (1, '支付宝支付')
    )

    total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='订单总价')
    real_price = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='实际金额')
    order_number = models.CharField(max_length=64, verbose_name='订单号')
    order_status = models.SmallIntegerField(choices=ORDER_STATUS_CHOICES, default=0, verbose_name='订单状态')
    pay_type = models.SmallIntegerField(choices=PAY_TYPE_CHOICES, default=1, verbose_name='支付方式')
    order_desc = models.TextField(default='', blank=True, null=True, max_length=300, verbose_name='订单描述')
    pay_time = models.DateTimeField(null=True, blank=True, verbose_name='支付时间')
    user = models.ForeignKey(to=UserModel, on_delete=models.DO_NOTHING, related_name='user_orders', db_constraint=False,
                             verbose_name='下单用户')

    # 优惠券
    def coupon(self):
        # 外键关联查询优惠券信息
        coupon_related = self.to_coupons.first()
        # 拼接优惠券信息
        if coupon_related:
            return {
                "id": coupon_related.coupon.id,
                "name": coupon_related.coupon.name,
                "sale": coupon_related.coupon.sale,
                "discount": coupon_related.coupon.discount,
                "condition": coupon_related.coupon.condition
            }
        else:
            return {}

    class Meta:
        db_table = 'dx_orders'
        verbose_name_plural = '订单记录表'

    def __str__(self):
        return "%s 总价：%s，实付金额：%s" % (self.name, self.total_price, self.real_price)


class OrderDetailModel(BaseModel):
    order = models.ForeignKey(to=OrderModel, related_name='order_detail', on_delete=models.CASCADE, db_constraint=False,
                              verbose_name='订单')
    doctor = models.ForeignKey(to=DoctorModel, related_name='doctor_order', on_delete=models.DO_NOTHING,
                               db_constraint=False, verbose_name='医生')
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='咨询原价')
    real_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='实际价格')
    discount_name = models.CharField(max_length=100, default="", verbose_name='优惠类型')

    class Meta:
        db_table = 'dx_order_details'
        verbose_name_plural = '订单详情表'

    def __str__(self):
        return self.doctor.name